package com.valuedaas.schoolsafety.util;

import com.valuedaas.schoolsafety.common.Constants;
import com.valuedaas.schoolsafety.common.base.Result;
import com.valuedaas.schoolsafety.controller.user.vo.User;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class WebUtil {

    /**
     * Get Request from
     * org.springframework.web.context.request.RequestContextHolder
     * WebUtil需要配置在web.xml的过滤器中 注意不能获得上传文件的Request
     *
     * @return HttpServletRequest
     */
    public static HttpServletRequest getRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        return request;
    }

    public static HttpServletResponse getResponse() {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getResponse();
        return response;

    }

    /**
     * 获得用户身份对对象
     *
     * @return User
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    public static User getSessionUser() {
        User user = null;
        Object obj = RequestContextHolder.getRequestAttributes().getAttribute(Constants.SESSION_KEY,
                RequestAttributes.SCOPE_SESSION);

        if (obj == null) {
            return null;
        }
        if (obj instanceof User) {
            return (User) obj;
        }

        if (obj instanceof Map) {
            Map map = (Map) obj;
            if (map != null) {
                try {
                    BeanUtils.populate(user, map);
                } catch (Exception e) {
                    // ignore
                }
            }
        }
        return user;

    }

    public static String logout() {
        HttpServletRequest request = WebUtil.getRequest();
        HttpServletResponse response = WebUtil.getResponse();
        request.getSession().invalidate();
        Cookie cookie = new Cookie(Constants.REMEMBERME_COOKIE, "");
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        return Result.ok("登出成功", null);
    }

    public static void rememberMe(User user, String password, int remberDays) {
        String md5Pwd = SecurityUtil.genMd5Password(user.getUsername(), password);
        String rememberToken = SecurityUtil.encodeRememberToken(user.getUsername(), md5Pwd);
        Cookie cookie = new Cookie(Constants.REMEMBERME_COOKIE, rememberToken);
        cookie.setPath("/");
        cookie.setHttpOnly(false);
        cookie.setMaxAge(remberDays * 24 * 60 * 60);
        HttpServletResponse response = WebUtil.getResponse();
        response.addCookie(cookie);
    }

    public static void responseJson(int code, String message, HttpServletResponse response)
            throws IOException, ServletException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter pw = response.getWriter();
        pw.print(Result.error(code, message, null));
        pw.flush();
    }

    /**
     * 是否需要过滤
     *
     * @param url
     * @return
     */
    public static boolean isNoNeedPermission(String url) {
        for (Pattern pattern : Constants.NO_NEED_PERMISSION) {
            Matcher matcher = pattern.matcher(url);
            if (matcher.matches()) {
                return true;
            }
        }
        return false;
    }

    public static  boolean isSwaggerResources(String uri) {
        return uri.startsWith("webjars") || uri.startsWith("v2/api-docs") ||
                uri.startsWith("swagger");
    }

}
